package com.xtpt.disaster.utils;
import com.xtpt.disaster.common.PortalResult;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Arrays;

@Component
public final class DatabaseUtil {
    public static int entirelyBackup(String binPath, String dbHost,  String dbUsername, String dbPassword, String dbName, String dbOutputFile, String dbFilename)
            throws IOException, InterruptedException {
        String[] command = {"/bin/bash", "-c", binPath + "mysqldump -h" + dbHost + " -u" + dbUsername + " -p" + dbPassword + " " + dbName + " > " + dbOutputFile + "/" + dbFilename};
        System.out.println("MySQL 备份指令:");
        System.out.println(Arrays.stream(command).toArray());
        for (String s : command) {
            System.out.println(s);
        }
        System.out.println(command);
        int processComplete = -1;
        try {
            Process process = Runtime.getRuntime().exec(command);
            processComplete = process.waitFor();
            System.out.println("备份返回码:");
            System.out.println(processComplete);
        }
        catch (Exception e){
            System.out.println(e);
        }
        return processComplete;
    }
    public static  boolean incrementalBackup(){
        return true;
    }
    public static int recover(String binPath, String dbHost, String dbUsername, String dbPassword, String dbName, String dbOutputFile, String dbFilename)
            throws IOException, InterruptedException {

        String[] commandCreate = {"/bin/bash", "-c", binPath + "mysqladmin -h" + dbHost + " -u" + dbUsername + " -p" + dbPassword + " " + "create " + dbName};
        System.out.println("create sql 语句:");
        for (String s : commandCreate) {
            System.out.println(s);
        }
        Process processCreate = Runtime.getRuntime().exec(commandCreate);
        int processCreateComplete = processCreate.waitFor();
        System.out.println("恢复创建数据库返回码:");
        System.out.println(processCreateComplete);
        if (processCreateComplete != 0) {
            System.out.println("恢复时创建数据库失败;");
        }
        String[] command = {"/bin/bash", "-c", binPath + "mysql -h" + dbHost + " -u" + dbUsername + " -p" + dbPassword + " " + dbName + " < " + dbOutputFile + "/" + dbFilename};
        System.out.println("MySQL恢复指令:");
        for (String s : command) {
            System.out.println(s);
        }
        Process process = Runtime.getRuntime().exec(command);
        int processComplete = process.waitFor();
        System.out.println("恢复返回码:");
        System.out.println(processComplete);
        return processComplete;
    }
}
